/**
 * Copyright (c) 2014-2016 www.nryuncang.com. All Rights Reserved.
 */
package com.topisv.tms.service.print.impl;

import static com.google.common.base.Preconditions.checkArgument;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.topisv.tms.entity.EdiOrder;
import com.topisv.tms.entity.ExpressConfigure;
import com.topisv.tms.entity.ExpressStyle;
import com.topisv.tms.entity.work.WorkOrder;
import com.topisv.tms.entity.work.WorkTask;
import com.topisv.tms.mybatis.SqlMapDao;
import com.topisv.tms.repository.EdiOrderDao;
import com.topisv.tms.service.ExpressConfigureService;
import com.topisv.tms.service.LogisticsMailNoService;
import com.topisv.tms.service.work.WorkOrderService;
import com.topisv.tms.service.work.WorkTaskService;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * 天天快递打印
 *
 * @author <a href=mailto:zhangweize@nryuncang.com>zhangweize</a>
 * @version 0.0.16
 */
@Component
public class TTKDEXPrintServiceImpl extends AbstractPrintService {
	
	private static final Logger logger = LoggerFactory.getLogger(TTKDEXPrintServiceImpl.class);

	
	@Autowired
	private WorkTaskService workTaskService;
	@Autowired
	private ExpressConfigureService expressConfigureService;
	@Autowired
	private SqlMapDao sqlMapDao;
	@Autowired
	private WorkOrderService workOrderService;
	@Autowired
	private LogisticsMailNoService logisticsMailNoService;
	@Autowired
	private EdiOrderDao ediOrderDao;

	@Override
	@Transactional(readOnly = false, rollbackFor = Exception.class)
	@SuppressWarnings("unchecked")
	public List<EdiOrder> doGetExpressNo(List<String> orderNoList, ExpressStyle template, String taskCode) throws Exception {

		// 第一步:得到基础信息如作业任务，订单列表、仓库信息、配置信息
		WorkTask workTask = workTaskService.loadTaskByCode(taskCode);
		ExpressConfigure expressConfigure = expressConfigureService.findByWarehouseAndCompany(workTask.getWarehouseCode(), template.getLogisticsCompany().getCompanyCode());
		
		List<EdiOrder> ediOrderList = sqlMapDao.selectList("ediOrderMapper.getEdiOrderListByOrdeno", orderNoList);
		
		// 第二步:循环订单
		for (EdiOrder ediOrder : ediOrderList) {

			WorkOrder workOrder = workOrderService.loadOrder(ediOrder.getBatchTaskCode(), ediOrder.getOrdeno());
			
			if (workOrder.getEbillNo() == null || "cbill".equals(workOrder.getBillType())
					|| !template.getLogisticsCompany().getCompanyCode().equals(workOrder.getExpressCompany())) {
				
				// 取号段
//				List<LogisticsMailNo> logisticsMailNos = logisticsMailNoService.getLogisticsMailNo("pending",template.getLogisticsCompany().getCompanyCode(), ediOrder.getWarehouseCode(), 1);
                String mailNo = logisticsMailNoService.getLogisticsMailNo(ediOrder.getOrdeno(), template.getLogisticsCompany().getCompanyCode(), ediOrder.getWarehouseCode());
				
				// 拼装报文
				String content = getTTKDEXXml(ediOrder, expressConfigure);
				logger.info("{}=天天取单号报文={}", ediOrder.getOrdeno(), content);
				
				// 发送天天接口接口,解析返回值，赋值
				String returnData = resturnTTKDEXResult(content, expressConfigure);
				logger.info("{}=天天取单号返回的报文={}", ediOrder.getOrdeno(), returnData);

				////{"data":[{"key":"PD1470030281455157","packageCode":"2","package":"杭州公司包","result":"浙 杭州"}]}		
				List<Map<String, String>> mapListJson = null;
				try {
				    JSONObject resultData = JSONObject.fromObject(returnData);
				    JSONArray jsonArray = JSONArray.fromObject(resultData.get("data"));	
				    mapListJson = (List<Map<String, String>>) jsonArray;
				} catch (Exception ex) {
				    logger.error("调用天天接口获取大头笔错误：天天系统崩溃，返回报文非法。", ex);
				    throw new RuntimeException("调用天天接口获取大头笔错误：天天系统崩溃，返回报文非法。", ex);
				}
				Map<String, String> resultMap = new HashMap<>();
				for (int i = 0; i < mapListJson.size(); i++) {
					Map<String, String> obj = mapListJson.get(i);
					for (Entry<String, String> entry : obj.entrySet()) {
						String strkey = entry.getKey();
						String strval = entry.getValue();
						resultMap.put(strkey, strval);
					}
				}
				
				if (resultMap != null && resultMap.size() != 0) {
					String result = resultMap.get("result"); // 大头笔
					String packageCode = resultMap.get("packageCode"); // 包编号
					String destCode = resultMap.get("package"); // 打包区域
					ediOrder.setMailNo(mailNo);
					ediOrder.setDestCode(destCode);
					ediOrder.setOriginCode(result);
					ediOrder.setRemark(packageCode);
					ediOrder.setCacode(template.getLogisticsCompany().getCompanyCode());//快递公司代码
					ediOrder.setCaname(template.getLogisticsCompany().getCompanyName());//快递公司名称
				} else {
					logger.error("{}=天天获取大头笔信息失败={}",ediOrder.getOrdeno(),returnData);
					throw new RuntimeException(ediOrder.getOrdeno()+"=获取天天信息获取大头笔失败="+ returnData);
				}

			}
		}
		ediOrderDao.save(ediOrderList);
		return ediOrderList;
	}

	/**
	 * 发送天天快递接口 post，返回请求结果
	 * 
	 *
	 * @param content
	 *            报文
	 * @param expressConfigure
	 *            配置信息
	 * @return
	 * @throws Exception
	 *             [参数说明]
	 * @author <a href=mailto:zhangweize@nryuncang.com>zhangweize</a>
	 * @version 0.0.16
	 */
	private String resturnTTKDEXResult(String content, ExpressConfigure expressConfigure) throws Exception {
		String url = expressConfigure.getUrl();
		// 校验请求地址
		checkArgument(StringUtils.isNotEmpty(url), String.format("TTDEX请求地址 is empty"));
		List<NameValuePair> parameters = new ArrayList<NameValuePair>();
		parameters.add(new BasicNameValuePair("arg1", "手机接口"));
		parameters.add(new BasicNameValuePair("arg2", "通用_取大头笔"));
		parameters.add(new BasicNameValuePair("arg3", content));
		return super.requestExpressNo(url, parameters);
	}

	/**
	 * 天天快递 xml报文
	 * 
	 *
	 * @param order
	 *            订单信息
	 * @param expressConfigure
	 *            天天快递配置信息
	 * @return [参数说明]
	 * @author <a href=mailto:zhangweize@nryuncang.com>zhangweize</a>
	 * @version 0.0.16
	 */
	private String getTTKDEXXml(EdiOrder order, ExpressConfigure expressConfigure) {
		
		JSONObject dataJson = new JSONObject();
		dataJson.put("key", order.getOrdeno());
		dataJson.put("prov", order.getProvna());
		dataJson.put("city", order.getCityna());
		dataJson.put("area", order.getDistna());
		
		JSONArray jsonArray = new JSONArray();
		jsonArray.add(dataJson);
		
		JSONObject json = new JSONObject();
		json.put("site", expressConfigure.getCompanyName());
		json.put("cus", expressConfigure.getWarehouseName());
		json.put("pasaword", expressConfigure.getPassword());
		json.put("data", jsonArray);
		
		return json.toString();
	}

}
